﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using MqttModel;
using Qiniu.Http;
using Qiniu.Util;

namespace rfid9500_Mqtt
{
    public class QiniuTools
    {
        static string ak = "-By1Udngz-42yvitskmKN7RJUzca4TupWduPabtz"; // 替换成实际的ak
        static string sk = "wPv0_BF2hotVGVmhEBgSYLlITp3nC1xmgu6_7_wO"; // 替换成实际的sk
        static Mac mac = new Mac(ak, sk);
        static long stms = 0;

        public static long STMS
        {
            get { return stms; }
        }

        public static void Catapic()
        {
            var c = DateTimeToTimeStamp();
            Console.WriteLine("c{0}, stms {1}",c,stms);
            if (c > stms)
            {
                stms = c;

                string body = ""; // "{\"data\":{ \"name\":\"test\"},\"params\":{ \"groups\":[\"ylxue_face_group_id2020\"]}}"; // 根据实际的API, 替换成实际的http body
                HttpManager http = new HttpManager();
                string namespaceId = "lexunbao28181";
                string streamId = "31011500991320007505";
                string url =
                    $"http://qvs.qiniuapi.com/v1/namespaces/{namespaceId}/streams/{streamId}/snap"; // 替换成实际的url,此处以[API创建流](https://developer.qiniu.com/qvs/6734/create-flow)为例
                Uri uri = new Uri(url);
                string contentType = "application/json";
                // 如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空
                //  如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空
                //  如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空

                string token = qiniutoken(mac, uri, body, contentType, "POST"); // 最后一个参数，根据实际请求替换
                HttpResult ret = http.PostJson(url, body, token);
                Console.WriteLine(ret.Text);
                Console.WriteLine(stms);
                // getapic();
            }
        }

        public static long DateTimeToTimeStamp()
        {
            return (long)
                (
                    DateTime.Now.ToUniversalTime()
                    - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                ).TotalSeconds;
        }

        public static void getapic()
        {
            string body = ""; // "{\"data\":{ \"name\":\"test\"},\"params\":{ \"groups\":[\"ylxue_face_group_id2020\"]}}"; // 根据实际的API, 替换成实际的http body
            HttpManager http = new HttpManager();
            string namespaceId = "lexunbao28181";
            string streamId = "31011500991320007505";
            string url =
                $"http://qvs.qiniuapi.com/v1/namespaces/{namespaceId}/streams/{streamId}/snapshots?type=2&start={stms}&end={stms + 5}&marker=&line=1"; // 替换成实际的url,此处以[API创建流](https://developer.qiniu.com/qvs/6734/create-flow)为例
            Console.WriteLine(url);
            Uri uri = new Uri(url);
            string contentType = "application/x-www-form-urlencoded";
            // 如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空
            //  如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空
            //  如果http body为空时(例如Get请求), contentType设为application/x-www-form-urlencoded或者为空

            string token = qiniutoken(mac, uri, body, contentType, "GET"); // 最后一个参数，根据实际请求替换
            HttpResult ret = http.Get(url, token);
            Console.WriteLine(ret.Text);
        }

        public static string qiniutoken(
            Mac mac,
            Uri url,
            String body,
            String contentType,
            String method
        )
        {
            // input path and host and rawquery
            string path = url.AbsolutePath;
            string host = url.Host;
            string rawquery = url.Query;
            var data = new System.Text.StringBuilder();
            data.AppendFormat("{0} {1}", method, path);
            if (rawquery != String.Empty)
                data.AppendFormat("{0}", rawquery);
            data.AppendFormat("\nHost: {0}", host);
            if (contentType != String.Empty)
                data.AppendFormat("\nContent-Type: {0}", contentType);
            data.Append("\n\n");
            if (contentType != String.Empty && contentType != "application/octet-stream")
                data.Append(body);
            String sdata = data.ToString();
            Console.WriteLine(sdata);
            HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(mac.SecretKey));
            byte[] digest = hmac.ComputeHash(Encoding.UTF8.GetBytes(sdata));
            string qiniuToken = String.Format(
                "Qiniu {0}:{1}",
                mac.AccessKey,
                Base64.UrlSafeBase64Encode(digest)
            );
            //string qiniuToken = String.Format("Qiniu {0}:{1}", mac.AccessKey, System.Convert.ToBase64String(digest).Replace("/", "+").Replace("+", "-"));
            Console.WriteLine(qiniuToken);
            return qiniuToken;
        }
    }
}
